# -*- coding: utf-8 -*-

import os
import os.path
import string
import re
import wx
import wx.aui
import wx.lib.newevent

# ---------- My Modules ---------- #
from loadSetting import *
import optionVar
import settingEditor
import tabpadCtrl
import outputCtrl
import fileListCtrl
import connectToMaya
import openFileCodingDialog
import statusbarCtrl


class MayapadWindow(wx.Frame):
	def __init__(self, parent, file = ''):
		
		self.parent = parent
		title = 'Mayapad'
		
		# Get last window pos & width
		if optionVar.hasOption('WindowWidth'):
			frameW = int(optionVar.getOption('WindowWidth'))
			frameH = int(optionVar.getOption('WindowHeight'))
		else:
			frameW = -1
			frameH = -1
		if optionVar.hasOption('WindowPosX'):
			frameX = int(optionVar.getOption('WindowPosX'))
			frameY = int(optionVar.getOption('WindowPosY'))
		else:
			frameX = -1
			frameY = -1
			
		self.frame = wx.Frame.__init__(self, parent, -1, title,
									   pos=(frameX,frameY),
									   size=(frameW,frameH))
		#self.panel=wx.Panel(self)
		self.FontSettings()
		self.LoadIcons()
		self.CreateMenu()
		self.statusBar = statusbarCtrl.StatusbarCtrl(self)
		self.SetStatusBar(self.statusBar)
		
		# tell FrameManager to manage this frame
		self._mgr = wx.aui.AuiManager()
		# ----- Appearance ----- #
		"""
		self._mgr.GetArtProvider().SetColor(
			wx.aui.AUI_DOCKART_INACTIVE_CAPTION_COLOUR,
			'#61AEFB')
		self._mgr.GetArtProvider().SetColor(
			wx.aui.AUI_DOCKART_INACTIVE_CAPTION_GRADIENT_COLOUR,
			'#418EFB')
		self._mgr.GetArtProvider().SetColor(
			wx.aui.AUI_DOCKART_INACTIVE_CAPTION_TEXT_COLOUR,
			'#FFFFFF')
		"""
		#self.DoUpdate()
		
		self._mgr.SetManagedWindow(self)
		
		self._mgr.AddPane(self.CreateFileListCtrl(),
						  wx.aui.AuiPaneInfo().Name("fileList").Caption("File List").
						  Left().Layer(1).Position(1).
						  CloseButton(True).MaximizeButton(True))
		
		self._mgr.AddPane(self.CreateOutputCtrl(),
						  wx.aui.AuiPaneInfo().Name("output").Caption("Output").
						  Bottom().Layer(1).Position(1).
						  CloseButton(True).MaximizeButton(True))
						  
		
		self._mgr.AddPane(self.CreateTabpad(),
						  wx.aui.AuiPaneInfo().Name("test1").CenterPane()
						  )
		
		self._mgr.AddPane(self.CreateToolBar(), wx.aui.AuiPaneInfo().
						  Name("tb1").Caption("Big Toolbar").
						  ToolbarPane().Top().
						  LeftDockable(False).RightDockable(False))
		
		self._mgr.Update()
		# ----- Bind ----- #
		self.Bind(wx.aui.EVT_AUI_PANE_CLOSE, self.OnPaneClose)
		self.Bind(wx.EVT_SIZE , self.OnSize)
		self.Bind(wx.EVT_MOVE, self.OnMove)
		self.Bind(wx.EVT_CLOSE, self.OnClose)
		
		# ----- icon ----- #
		if not sys.platform=='darwin':
			_icon = wx.Icon( getIconPath('Mayapad'), wx.BITMAP_TYPE_ICO)
			self.SetIcon(_icon)
		
		# ----- arg ----- #
		if os.path.isfile(file):
			self.OpenFileToNewTab(file)
		
		# ----- Connect To Maya ----- #
		self.serverHost = 'localhost'
		self.serverPort = 2222
		if optionVar.hasOption('socket_address'):
			self.serverHost = str(optionVar.getOption('Socket_Address'))
		if optionVar.hasOption('socket_port'):
			self.serverPort = int(optionVar.getOption('Socket_Port'))
		self.connect(0)
		
		# ----- Values ----- #
		self.isFinishing = False # Flag for socket closing when terminating.
		
	def FontSettings(self):
		# ---------- Default Font settings ---------- #
		fontFamiliy=wx.DEFAULT
		fontStyle=wx.NORMAL
		if sys.platform=='win32':
			self.Font_TabActive = wx.Font(7,
										  fontFamiliy,
										  fontStyle,
										  wx.BOLD,
										  faceName="Microsoft Sans Serif")
			self.Font_TabInActive = wx.Font(7,
											fontFamiliy,
											fontStyle,
											wx.NORMAL,
											faceName="Microsoft Sans Serif")
			# Output
			Output_fontSize=8
			Output_fontFamiliy=fontFamiliy
			Output_fontStyle=fontStyle
			Output_fontWeight=wx.NORMAL
			Output_fontName="Courier New"
			
			# FileList
			FileList_fontSize=9
			FileList_fontFamiliy=fontFamiliy
			FileList_fontStyle=fontStyle
			FileList_fontWeight=wx.NORMAL
			FileList_fontName='Arial'
			
			# Editor Main
			Editor_fontSize=9
			Editor_fontFamiliy=wx.MODERN
			Editor_fontStyle=fontStyle
			Editor_fontWeight=wx.NORMAL
			Editor_fontName='Courier'
			
		elif sys.platform=='darwin':
			self.Font_TabActive = wx.Font(7, fontFamiliy,
										  fontStyle,
										  wx.BOLD,
										  faceName="Arial")
			self.Font_TabInActive = wx.Font(7, fontFamiliy,
											fontStyle,
											wx.NORMAL,
											faceName="Arial")
			# Output
			Output_fontSize=12
			Output_fontFamiliy=fontFamiliy
			Output_fontStyle=fontStyle
			Output_fontWeight=wx.NORMAL
			Output_fontName="Arial"
			
			# FileList
			FileList_fontSize=9
			FileList_fontFamiliy=fontFamiliy
			FileList_fontStyle=fontStyle
			FileList_fontWeight=wx.NORMAL
			FileList_fontName='Arial'
			
			# Editor Main
			Editor_fontSize=9
			Editor_fontFamiliy=wx.MODERN
			Editor_fontStyle=fontStyle
			Editor_fontWeight=wx.NORMAL
			Editor_fontName='Courier'
			
		else:
			self.Font_TabActive = wx.Font(7, fontFamiliy,
										  fontStyle,
										  wx.BOLD,
										  faceName="Helvetica")
			self.Font_TabInActive = wx.Font(7, fontFamiliy,
											fontStyle,
											wx.NORMAL,
											faceName="Helvetica")
			# Output
			Output_fontSize=6
			Output_fontFamiliy=fontFamiliy
			Output_fontStyle=fontStyle
			Output_fontWeight=wx.NORMAL
			Output_fontName="Courier"
			
			# FileList
			FileList_fontSize=7
			FileList_fontFamiliy=fontFamiliy
			FileList_fontStyle=fontStyle
			FileList_fontWeight=wx.NORMAL
			FileList_fontName='Helvetica'
			
			# Editor Main
			Editor_fontSize=9
			Editor_fontFamiliy=wx.MODERN
			Editor_fontStyle=fontStyle
			Editor_fontWeight=wx.NORMAL
			Editor_fontName='Courier'
			
		# ---------- Restore saved settings ---------- #
		# Output
		if optionVar.hasOption('Output_Size'):
			Output_fontSize = int(optionVar.getOption('Output_Size'))
		if optionVar.hasOption('Output_Family'):
			Output_fontFamiliy = int(optionVar.getOption('Output_Family'))
		if optionVar.hasOption('Output_Style'):
			Output_fontStyle = int(optionVar.getOption('Output_Style'))
		if optionVar.hasOption('Output_Weight'):
			Output_fontWeight = int(optionVar.getOption('Output_Weight'))
		if optionVar.hasOption('Output_Font'):
			Output_fontName = optionVar.getOption('Output_Font')
		self.Font_Output = wx.Font(
			Output_fontSize,
			Output_fontFamiliy,
			Output_fontStyle,
			Output_fontWeight,
			faceName=Output_fontName)
		# FileList
		if optionVar.hasOption('FileList_Size'):
			FileList_fontSize = int(optionVar.getOption('FileList_Size'))
		if optionVar.hasOption('FileList_Family'):
			FileList_fontFamiliy = int(optionVar.getOption('FileList_Family'))
		if optionVar.hasOption('FileList_Style'):
			FileList_fontStyle = int(optionVar.getOption('FileList_Style'))
		if optionVar.hasOption('FileList_Weight'):
			FileList_fontWeight = int(optionVar.getOption('FileList_Weight'))
		if optionVar.hasOption('FileList_Font'):
			FileList_fontName = optionVar.getOption('FileList_Font')
		self.Font_Tree = wx.Font(
			FileList_fontSize,
			FileList_fontFamiliy,
			FileList_fontStyle,
			FileList_fontWeight,
			faceName=FileList_fontName)
		# Editor Main
		if optionVar.hasOption('Editor_Size'):
			Editor_fontSize = int(optionVar.getOption('Editor_Size'))
		if optionVar.hasOption('Editor_Family'):
			Editor_fontFamiliy = int(optionVar.getOption('Editor_Family'))
		if optionVar.hasOption('Editor_Style'):
			Editor_fontStyle = int(optionVar.getOption('Editor_Style'))
		if optionVar.hasOption('Editor_Weight'):
			Editor_fontWeight = int(optionVar.getOption('Editor_Weight'))
		if optionVar.hasOption('Editor_Font'):
			Editor_fontName = optionVar.getOption('Editor_Font')
		self.Font_Editor = wx.Font(
			Editor_fontSize,
			Editor_fontFamiliy,
			Editor_fontStyle,
			Editor_fontWeight,
			faceName=Editor_fontName)
		
	def OnPaneClose(self,event):
		caption = event.GetPane().caption
		if caption == 'File List':
			if self.menuShowFileList.IsChecked():
				self.menuWindow.Check(self.MENU_WINDOW_SHOWFILELIST, False)
			else:
				self.menuWindow.Check(self.MENU_WINDOW_SHOWFILELIST, True)
		if caption == 'Output':
			if self.menuShowOutput.IsChecked():
				self.menuWindow.Check(self.MENU_WINDOW_SHOWOUTPUT, False)
			else:
				self.menuWindow.Check(self.MENU_WINDOW_SHOWOUTPUT, True)
				
	def OnSize(self,event):
		size = self.GetClientSize()
		optionVar.saveOption('WindowWidth', size[0])
		optionVar.saveOption('WindowHeight', size[1])
		
	def OnMove(self, event):
		self.posX, self.posY = event.GetPosition()
		optionVar.saveOption('WindowPosX', self.posX)
		optionVar.saveOption('WindowPosY', self.posY)
		
	# ==================== Load Icons ==================== #
	def LoadIcons(self):
		iconFile = getResPath("Py.png")
		self.pyIco = wx.Bitmap(iconFile, type=wx.BITMAP_TYPE_PNG)
		iconFile = getResPath("mel.png")
		self.melIco = wx.Bitmap(iconFile, type=wx.BITMAP_TYPE_PNG)
		iconFile = getResPath("RunAll.png")
		self.RunAll = wx.Bitmap(iconFile, type=wx.BITMAP_TYPE_PNG)
		iconFile = getResPath("RunSelection.png")
		self.RunSelection = wx.Bitmap(iconFile, type=wx.BITMAP_TYPE_PNG)
		iconFile = getResPath("scriptDir.png")
		self.scriptDir = wx.Bitmap(iconFile, type=wx.BITMAP_TYPE_PNG)
		iconFile = getResPath("scriptDir_open.png")
		self.scriptDir_open = wx.Bitmap(iconFile, type=wx.BITMAP_TYPE_PNG)
		self.normalFile = wx.ArtProvider_GetBitmap(wx.ART_NORMAL_FILE,
												   wx.ART_OTHER,
												   wx.Size(16,16))
		self.folder = wx.ArtProvider_GetBitmap(wx.ART_FOLDER,
											   wx.ART_OTHER,
											   wx.Size(16,16))
		self.folderOpen = wx.ArtProvider_GetBitmap(wx.ART_FILE_OPEN,
												   wx.ART_OTHER,
												   wx.Size(16,16))
		
	# ==================== Menu ==================== #
	def CreateMenu(self):
		self.MENU_NEW = wx.NewId()
		self.MENU_OPEN = wx.NewId()
		self.MENU_OPEN_AS = wx.NewId()
		self.MENU_SAVE = wx.NewId()
		self.MENU_SAVE_AS = wx.NewId()
		self.MENU_CLOSE = wx.NewId()
		self.MENU_SAVE_ALL_TAB = wx.NewId()
		self.MENU_CONNECT = wx.NewId()
		self.MENU_EDIT_UNDO = wx.NewId()
		self.MENU_EDIT_REDO = wx.NewId()
		self.MENU_EDIT_CUT = wx.NewId()
		self.MENU_EDIT_COPY = wx.NewId()
		self.MENU_EDIT_PASTE = wx.NewId()
		self.MENU_EDIT_DELETE = wx.NewId()
		self.MENU_EDIT_SELECT_ALL = wx.NewId()
		self.MENU_EDIT_SETTINGS = wx.NewId()
		self.MENU_FIND = wx.NewId()
		self.MENU_FIND_NEXT = wx.NewId()
		self.MENU_FIND_REPLACE = wx.NewId()
		self.MENU_RUN_ALL = wx.NewId()
		self.MENU_RUN_SELECTION = wx.NewId()
		self.MENU_WINDOW_SHOWOUTPUT = wx.NewId()
		self.MENU_WINDOW_SHOWFILELIST = wx.NewId()
		self.MENU_TEST = wx.NewId()
		
		menuBar = wx.MenuBar()
		
		menuFile = wx.Menu()
		menuFile.Append(self.MENU_OPEN, "O&pen File\tAlt-O", "Open File")
		menuFile.Append(self.MENU_OPEN_AS, "O&pen File As", "Open File As")
		menuFile.Append(self.MENU_SAVE, "S&ave File\tCtrl-S", "Save File")
		menuFile.Append(self.MENU_SAVE_AS, "S&ave File As..",
						"Save File As")
		menuFile.Append(self.MENU_SAVE_ALL_TAB, "S&ave All Tab",
						"Save All Tabs")
		menuFile.AppendSeparator()
		menuFile.Append(self.MENU_CONNECT, "C&onnect to Maya",
						"Connect to Maya")
		menuFile.AppendSeparator()
		menuFile.Append(self.MENU_CLOSE, "E&xit\tAlt-Q", "Exit Mayapad")
		
		menuEdit = wx.Menu()
		menuEdit.Append(self.MENU_EDIT_UNDO,
						'&Undo\tCtrl+Z', 'Undo last operation')
		menuEdit.Append(self.MENU_EDIT_REDO,
						'&Redo\tCtrl+Y', 'Redo last operation')
		menuEdit.AppendSeparator()
		menuEdit.Append(self.MENU_EDIT_CUT,
						'&Cut\tCtrl+X', 'Cut the Selection')
		menuEdit.Append(self.MENU_EDIT_COPY,
						'&Copy\tCtrl+C', 'Copy the Selection')
		menuEdit.Append(self.MENU_EDIT_PASTE,
						'&Paste\tCtrl+V', 'Paste text from clipboard')
		menuEdit.Append(self.MENU_EDIT_DELETE,
						'&Delete', 'Delete the selected text')
		menuEdit.AppendSeparator()
		menuEdit.Append(self.MENU_EDIT_SELECT_ALL,
						'Select &All\tCtrl+A', 'Select the entire text')
		menuEdit.AppendSeparator()
		menuEdit.Append(self.MENU_EDIT_SETTINGS,
						'Edit Settings', 'Edit Settings')
		
		menuFind = wx.Menu()
		menuFind.Append(self.MENU_FIND,
						'&Find\tCtrl+F', 'Find word')
		menuFind.Append(self.MENU_FIND_REPLACE,
						'&Replace\tCtrl+R', 'Replace word')
		menuDisplay = wx.Menu()
		
		self.menuWindow = wx.Menu()
		self.menuShowFileList = self.menuWindow.Append(self.MENU_WINDOW_SHOWFILELIST,
													   "Show FileList",
													   "Show FileList",
													   kind = wx.ITEM_CHECK)
		self.menuShowOutput = self.menuWindow.Append(self.MENU_WINDOW_SHOWOUTPUT,
													 "Show Output",
													 "Show Output",
													 kind = wx.ITEM_CHECK)
		menuRun = wx.Menu()
		menuRun.Append(self.MENU_RUN_ALL,
					   "&Run All\tCtrl+Shift+R",
					   "Run All")
		menuRun.Append(self.MENU_RUN_SELECTION,
					   "&Run Selection\tCtrl+Enter",
					   "Run Selection")
		
		menuTool = wx.Menu()
		
		menuHelp = wx.Menu()
		
		menuBar.Append(menuFile, "&File")
		menuBar.Append(menuEdit, "&Edit")
		menuBar.Append(menuFind, "&Find")
		menuBar.Append(menuDisplay, "&Display")
		menuBar.Append(self.menuWindow, "&Window")
		menuBar.Append(menuRun, "&Run")
		menuBar.Append(menuTool, "&Tool")
		menuBar.Append(menuHelp, "&Help")
		self.SetMenuBar(menuBar)
		# ----- Default Value ----- #
		self.menuWindow.Check(self.MENU_WINDOW_SHOWFILELIST, True)
		self.menuWindow.Check(self.MENU_WINDOW_SHOWOUTPUT, True)
		menuFind.Enable(self.MENU_FIND_REPLACE, False)
		# ----- Bind ----- #
		wx.EVT_MENU(self, self.MENU_OPEN, self.OnOpenFile)
		wx.EVT_MENU(self, self.MENU_OPEN_AS, self.OnOpenFileAs)
		wx.EVT_MENU(self, self.MENU_SAVE, self.OnSaveCurrentTab)
		wx.EVT_MENU(self, self.MENU_SAVE_AS, self.OnSaveCurrentTabAs)
		wx.EVT_MENU(self, self.MENU_SAVE_ALL_TAB, self.OnSaveAllTab)
		wx.EVT_MENU(self, self.MENU_CONNECT, self.connect)
		wx.EVT_MENU(self, self.MENU_CLOSE, self.OnClose)
		wx.EVT_MENU(self, self.MENU_EDIT_UNDO, self.OnUndo)
		wx.EVT_MENU(self, self.MENU_EDIT_REDO, self.OnRedo)
		wx.EVT_MENU(self, self.MENU_EDIT_CUT, self.OnCut)
		wx.EVT_MENU(self, self.MENU_EDIT_COPY, self.OnCopy)
		wx.EVT_MENU(self, self.MENU_EDIT_PASTE, self.OnPaste)
		wx.EVT_MENU(self, self.MENU_EDIT_DELETE, self.OnDelete)
		wx.EVT_MENU(self, self.MENU_EDIT_SELECT_ALL, self.OnSelectAll)
		wx.EVT_MENU(self, self.MENU_EDIT_SETTINGS, self.OnOpenSettingsWindow)
		wx.EVT_MENU(self, self.MENU_FIND, self.OnFind)
		wx.EVT_MENU(self, self.MENU_WINDOW_SHOWFILELIST, self.OnShowFileList)
		wx.EVT_MENU(self, self.MENU_WINDOW_SHOWOUTPUT, self.OnShowOutput)
		wx.EVT_MENU(self, self.MENU_RUN_ALL, self.OnRunAll)
		wx.EVT_MENU(self, self.MENU_RUN_SELECTION, self.OnRunSelection)
		
	# ==================== ToolBar ==================== #
	def CreateToolBar(self):
		tb2 = wx.ToolBar(self, -1, wx.DefaultPosition, wx.DefaultSize,
						 style = wx.NO_BORDER | wx.TB_FLAT | wx.TB_NODIVIDER )#wx.TB_TEXT
		tb2.SetToolBitmapSize(wx.Size(16,16))
		tb2_new = wx.ArtProvider_GetBitmap(wx.ART_NEW,
										   wx.ART_OTHER,
										   wx.Size(16, 16))
		tb2_fileOpen = wx.ArtProvider_GetBitmap(wx.ART_FILE_OPEN,
												wx.ART_OTHER,
												wx.Size(16, 16))
		tb2_fileSave = wx.ArtProvider_GetBitmap(wx.ART_FILE_SAVE,
												wx.ART_OTHER,
												wx.Size(16, 16))
		tb2_cut = wx.ArtProvider_GetBitmap(wx.ART_CUT,
										   wx.ART_OTHER,
										   wx.Size(16, 16))
		tb2_copy = wx.ArtProvider_GetBitmap(wx.ART_COPY,
											wx.ART_OTHER,
											wx.Size(16, 16))
		tb2_paste = wx.ArtProvider_GetBitmap(wx.ART_PASTE,
											 wx.ART_OTHER,
											 wx.Size(16, 16))
		tb2_undo = wx.ArtProvider_GetBitmap(wx.ART_UNDO,
											wx.ART_OTHER,
											wx.Size(16, 16))
		tb2_redo = wx.ArtProvider_GetBitmap(wx.ART_REDO,
											wx.ART_OTHER,
											wx.Size(16, 16))
		tb2_find = wx.ArtProvider_GetBitmap(wx.ART_FIND,
											wx.ART_OTHER,
											wx.Size(16, 16))
		tb2_findAndReplace = wx.ArtProvider_GetBitmap(wx.ART_FIND_AND_REPLACE,
													  wx.ART_OTHER,
													  wx.Size(16, 16))
		tb2.AddLabelTool(self.MENU_NEW, "New", tb2_new)
		tb2.AddLabelTool(self.MENU_OPEN, "Open", tb2_fileOpen)
		tb2.AddLabelTool(self.MENU_SAVE, "Save", tb2_fileSave)
		tb2.AddSeparator()
		tb2.AddLabelTool(self.MENU_EDIT_CUT, "Cut", tb2_cut)
		tb2.AddLabelTool(self.MENU_EDIT_COPY, "Copy", tb2_copy)
		tb2.AddLabelTool(self.MENU_EDIT_PASTE, "Paste", tb2_paste)
		tb2.AddSeparator()
		tb2.AddLabelTool(self.MENU_EDIT_UNDO, "Undo", tb2_undo)
		tb2.AddLabelTool(self.MENU_EDIT_REDO, "Redo", tb2_redo)
		tb2.AddSeparator()
		tb2.AddLabelTool(self.MENU_FIND, "Find", tb2_find)
		tb2.AddLabelTool(self.MENU_FIND_NEXT, "Find Next",
						 tb2_findAndReplace)
		tb2.AddSeparator()
		tb2.AddLabelTool(self.MENU_RUN_SELECTION, "RunSelection",
						 self.RunSelection)
		tb2.AddLabelTool(self.MENU_RUN_ALL, "RunAll", self.RunAll)
		
		self.Bind(wx.EVT_TOOL, self.OnNewFile, id=self.MENU_NEW)
		self.Bind(wx.EVT_TOOL, self.OnOpenFile, id=self.MENU_OPEN)
		self.Bind(wx.EVT_TOOL, self.OnSaveCurrentTab, id=self.MENU_SAVE)
		self.Bind(wx.EVT_TOOL, self.OnUndo, id=self.MENU_EDIT_UNDO)
		self.Bind(wx.EVT_TOOL, self.OnRedo, id=self.MENU_EDIT_REDO)
		self.Bind(wx.EVT_TOOL, self.OnCut, id=self.MENU_EDIT_CUT)
		self.Bind(wx.EVT_TOOL, self.OnCopy, id=self.MENU_EDIT_COPY)
		self.Bind(wx.EVT_TOOL, self.OnPaste, id=self.MENU_EDIT_PASTE)
		self.Bind(wx.EVT_TOOL, self.OnFind, id=self.MENU_FIND)
		self.Bind(wx.EVT_TOOL, self.OnFindNext, id=self.MENU_FIND_NEXT)
		self.Bind(wx.EVT_TOOL, self.OnRunSelection, id=self.MENU_RUN_SELECTION)
		self.Bind(wx.EVT_TOOL, self.OnRunAll, id=self.MENU_RUN_ALL)
		
		tb2.Realize()
		return tb2
	
	def OnOpenSettingsWindow(self, event):
		settingWin = settingEditor.SettingsFrame(self,
						   style=wx.DEFAULT_FRAME_STYLE | wx.TINY_CAPTION_HORIZ)
		settingWin.CenterOnParent(wx.BOTH)
		settingWin.Show(True)
		
			
	# ==================== Status Bar ==================== #
	def statusFromThread(self, event):
		self.DisplayToStatusBar(event.status, event.append)
	
	def DisplayToStatusBar(self, text, append=False):
		if append:
			currentText = self.statusBar.GetStatusText()
			self.statusBar.setText(currentText+text)
		else:
			self.statusBar.setText(text)
			
	def setCodingStatusBar(self, coding):
			self.statusBar.setCoding(coding)
			
	# ==================== FileList Ctrl ==================== #
	def OnShowFileList(self, event):
		print 'OnShowFileList'
		if self.menuShowFileList.IsChecked():
			print 'Show FileList'
			self._mgr.GetPane("fileList").Show()
			self._mgr.Update()
		else:
			print 'Hide FileList'
			self._mgr.GetPane("fileList").Hide()
			self._mgr.Update()
			
	def CreateFileListCtrl(self):
		self.fileListCtrl = fileListCtrl.FileListCtrl(
			self,
			font = self.Font_Tree,
			folderIcon=self.folder,
			folderOpenIcon=self.folderOpen,
			scriptFolderIcon=self.scriptDir,
			scriptFolderOpenIcon=self.scriptDir_open,
			normalFileIcon=self.normalFile,
			pythonIcon=self.pyIco,
			melIcon=self.melIco)
		self.Bind(fileListCtrl.EVT_FILELIST_OPENFILE, self.OnOpenThisFile)
		return self.fileListCtrl
	
	def IsNewFilePath(self, path):
		# If this path is in self.scriptDirList or child of directory,
		# return False.
		return self.fileListCtrl.IsNewFilePath(path)
	
	def GetFileListFont(self):
		return self.fileListCtrl.GetFont()
	
	def GetFileListTextColour(self):
		return self.fileListCtrl.GetTextColour()
	
	def GetFileListColour(self):
		return self.fileListCtrl.GetColour()
	
	def SetFileListFont(self, font):
		self.fileListCtrl.SetFont(font)
	
	def SetFileListTextColour(self, col):
		self.fileListCtrl.SetTextColour(col)
	
	def SetFileListColour(self, col):
		self.fileListCtrl.SetColour(col)
	
	# ==================== Output Ctrl ==================== #
	def OnShowOutput(self, event):
		print "(OnShowOutput)"
		if self.menuShowOutput.IsChecked():
			print 'Show Output'
			self._mgr.GetPane("output").Show()
			self._mgr.Update()
		else:
			print 'Hide Output'
			self._mgr.GetPane("output").Hide()
			self._mgr.Update()
	
	def CreateOutputCtrl(self):
		self.outputCtrl = outputCtrl.OutputCtrl(self, font=self.Font_Output)
		return self.outputCtrl
	
	def outputFromThread(self, event):
		self.AppendToOutput(event.output)
		
	def AppendToOutput(self, text):
		self.outputCtrl.appendText(text)
		
	def GetOutputFont(self):
		return self.outputCtrl.GetFont()
	
	def GetOutputTextColour(self):
		return self.outputCtrl.GetTextColour()
	
	def GetOutputColour(self):
		return self.outputCtrl.GetColour()
	
	def SetOutputFont(self, font):
		self.outputCtrl.SetFont(font)
	
	def SetOutputTextColour(self, col):
		self.outputCtrl.SetTextColour(col)
	
	def SetOutputColour(self, col):
		self.outputCtrl.SetColour(col)
	
	# ==================== Tabpad Ctrl ==================== #
	def CreateTabpad(self):
		self.tabpadCtrl = tabpadCtrl.TabpadCtrl(self,
												tabFont=self.Font_TabInActive,
												tabSelectedFont=self.Font_TabActive,
												editorFont=self.Font_Editor,
												normalFileIcon=self.normalFile,
												pythonIcon=self.pyIco,
												melIcon=self.melIco)
		self.Bind(tabpadCtrl.EVT_TABPAD_STATUS , self.OnTabpadStatus)
		self.Bind(tabpadCtrl.EVT_TABPAD_FILEOPENED, self.OnOpenedFile)
		self.Bind(tabpadCtrl.EVT_TABPAD_TABCHANGED, self.onTabChanged)
		return self.tabpadCtrl
	
	def OnOpenFile(self, event):
		self.tabpadCtrl.openFile()
		
	def OnOpenFileAs(self, event):
		dlg = openFileCodingDialog.OpenFileDialog(self)
		if dlg.ShowModal() == wx.ID_OK:
			self.tabpadCtrl.openFile(coding=dlg.coding)
		dlg.Destroy()
		
	def OnOpenThisFile(self, event):
		self.tabpadCtrl.openFileToNewTab(event.filePath)
		
	def OnNewFile(self, event):
		self.tabpadCtrl.newFile()
		
	def OnUndo(self, event):
		self.tabpadCtrl.undo()
	
	def OnRedo(self, event):
		self.tabpadCtrl.redo()
	
	def OnCut(self, event):
		self.tabpadCtrl.cut()
	
	def OnCopy(self, event):
		self.tabpadCtrl.copy()
	
	def OnPaste(self, event):
		self.tabpadCtrl.paste()
	
	def OnDelete(self, event):
		self.tabpadCtrl.clear()
	
	def OnSelectAll(self, event):
		self.tabpadCtrl.selectAll()
		
	def OnFind(self, event):
		self.tabpadCtrl.find()
		
	def OnFindNext(self, event):
		self.tabpadCtrl.findNext()
		
	def OnRunSelection(self, event):
		self.send(
			self.tabpadCtrl.getSelectedText(),
			code=self.tabpadCtrl.getCurrentExt()
			)
		
	def OnRunAll(self, event):
		self.send(
				self.tabpadCtrl.getText(),
				code=self.tabpadCtrl.getCurrentExt()
				)
		
	def OnCloseTab(self, event):
		closedTabTitle = self.tabpadCtrl.closeTab()
		
	def OnSaveCurrentTab(self, event):
		self.tabpadCtrl.saveTab()
		
	def OnSaveAllTab(self, event):
		self.tabpadCtrl.saveAllTab()
		
	def OnSaveCurrentTabAs(self, event):
		self.tabpadCtrl.saveTabAs()
		
	def OnTabpadStatus(self, event):
		"""
		Event from Tabpad.
		"""
		self.DisplayToStatusBar(event.output, append=event.append)
		pass
	
	def OnOpenedFile(self, event):
		"""
		Event when file was opened.
		If this path isn't in FileList, Add it.
		"""
		self.setCodingStatusBar(event.coding)
		if self.IsNewFilePath(os.path.dirname(event.filePath)):
			self.fileListCtrl.AddItem(os.path.dirname(event.filePath), True, False, False)
			
	def onTabChanged(self, event):
		self.setCodingStatusBar(event.coding)
		
	def GetTabpadFont(self):
		return self.tabpadCtrl.GetFont()
	
	def GetTabpadTextColour(self):
		return self.tabpadCtrl.GetTextColour()
	
	def GetTabpadColour(self):
		return self.tabpadCtrl.GetColour()
	
	def SetTabpadFont(self, font):
		self.tabpadCtrl.SetFont(font)
	
	def SetTabpadTextColour(self, col):
		self.tabpadCtrl.SetTextColour(col)
	
	def SetTabpadColour(self, col):
		self.tabpadCtrl.SetColour(col)
	
	# ==================== Communication with  Maya ==================== #
	def connect(self, event):
		print '(connect)'
		self.sockToMaya = connectToMaya.ConnectToMaya(self,
										self.serverHost,
										 self.serverPort)
		self.Bind(connectToMaya.EVT_CONNECTION_OUTPUT, self.outputFromThread)
		self.Bind(connectToMaya.EVT_CONNECTION_STATUS, self.statusFromThread)
		self.Bind(connectToMaya.EVT_CONNECTION_CLOSE, self.socketClosed)
		try:
			self.sockToMaya.start()
		except:
			self.DisplayToStatusBar('Connection Failed.')
		
	def disconnect(self, event):
		print '(disconnect)'
		if self.sockToMaya == None:
			self.DisplayToStatusBar('There is no connection.')
			return None
		
		self.sockToMaya.stop()
		
	def send(self, text, code):
		print '(send)'
		if self.sockToMaya== None:
			self.DisplayToStatusBar('No connection to Maya')
			return None
		
		if code!='py' and code!='mel':
			self.DisplayToStatusBar('Neither Python nor Mel.')
			return None
		
		self.DisplayToStatusBar('Send Script To Maya: ')
		self.DisplayToStatusBar(text, append=True)
		self.sockToMaya.sendScript(code, text)
		
	def socketClosed(self, event):
		if self.isFinishing:
			print '(socketClosed) Good bye!'
			#print ('(socketClosed) Socket successfully closed.
			# 'Now self destroy.')
			self.sockToMaya=None
			self.Destroy()
		else:
			self.sockToMaya=None
		
	# ==================== Close ==================== #
	def OnClose(self, event):
		self.tabpadCtrl.close()
		self.fileListCtrl.SaveDirSettings()
		if self.sockToMaya == None:
			self.Destroy()
		else:
			self.isFinishing = True
			print '(OnClose) disconnect connection before exit.'
			self.disconnect(0)


class MyApp(wx.App):
	def __init__(self):
		wx.App.__init__(self, redirect=False)
		
	def OnInit(self):
		if len(sys.argv)>1:
			self.frame = MayapadWindow(None, file = sys.argv[1])
		else:
			self.frame = MayapadWindow(None)
		self.SetTopWindow(self.frame)
		self.frame.Show(True)
		return 1


if __name__ == '__main__':
	app =MyApp()
	app.MainLoop()
